package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.service.DeviceManagementService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import java.util.List;

@RestController
@RequestMapping("/api/devices")
@RequiredArgsConstructor
public class DeviceController {
    private final DeviceManagementService deviceManagementService;

    @PostMapping
    public ResponseEntity<Device> createDevice(@RequestBody Device device) {
        return ResponseEntity.ok(deviceManagementService.createDevice(device));
    }

    @PostMapping("/{deviceId}/greenhouse/{greenhouseId}")
    public ResponseEntity<Device> bindDeviceToGreenhouse(
            @PathVariable Long deviceId,
            @PathVariable Long greenhouseId) {
        return ResponseEntity.ok(deviceManagementService.bindDeviceToGreenhouse(deviceId, greenhouseId));
    }

    @GetMapping
    public ResponseEntity<List<Device>> getAllDevices() {
        return ResponseEntity.ok(deviceManagementService.getAllDevices());
    }

    @GetMapping("/serial/{serialNumber}")
    public ResponseEntity<Device> getDeviceBySerialNumber(@PathVariable String serialNumber) {
        try {
            Device device = deviceManagementService.getDeviceBySerialNumber(serialNumber);
            return ResponseEntity.ok(device);
        } catch (EntityNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{deviceId}")
    public ResponseEntity<Void> deleteDevice(@PathVariable Long deviceId) {
        deviceManagementService.deleteDevice(deviceId);
        return ResponseEntity.ok().build();
    }
}